/* file : nd_connector.cpp
 * connector class of nd engine 
 *
 * all right reserved by neil duan 
 * 2009-5-8 23:25 
 */

#include "nd_common/nd_os.h"
#include "nd_appcpp/nd_connector.h"
//////////////////////////////////////////////////////////////////////////
//class NDConnector

NDConnector * htoConnector(nd_handle h)
{
	return (NDConnector*) (((nd_netui_handle)h)->user_data  );
}

NDConnector::NDConnector(NDINT32 maxmsg_num , NDINT32 maxid_start) 
{
	_h_connector = NULL ;
	msg_kinds = maxmsg_num;
	msg_base = maxid_start;
}

NDConnector::~NDConnector() 
{
	Destroy() ;
}

NDINT32 NDConnector::Open(NDINT8 *host, NDINT32 port, NDINT8 *protocol_name)
{
	NDINT8 *p;
	if(_h_connector) {
		return -1 ;
	}
	//connect to host
	if (protocol_name)
		p = (NDINT8 *)protocol_name;
	else
		p = (NDINT8 *)"tcp-connector";
	_h_connector = nd_object_create(p);

	if(!_h_connector){
		nd_logerror("connect error :%s!" AND nd_last_error());
		return -1;
	}

	//set message handle	
	nd_msgtable_create(_h_connector, msg_kinds, msg_base) ;
	
	//install_msg(_h_connector);

	if(-1==nd_connector_openex( _h_connector, (NDINT8 *)host,  (NDINT32)port ) ) {
		nd_logerror("connect error :%s!" AND nd_last_error()) ;
		nd_object_destroy(_h_connector,1) ;
		_h_connector = NULL ;
		return -1;
	}

	((nd_netui_handle)_h_connector)->user_data =(void*) this ;
	return 0 ;

}

NDINT32 NDConnector::Close(NDINT32 force)
{
	if(_h_connector) {
		return nd_connector_close(_h_connector, force) ;
	}
	return -1 ;
}


void NDConnector::Destroy()
{
	if(_h_connector && ((nd_netui_handle)_h_connector)->user_data ==(void*) this){
		nd_connector_close(_h_connector, 0) ;
		nd_msgtable_destroy(_h_connector);
		nd_object_destroy(_h_connector, 0) ;
	}
}

NDINT32 NDConnector::SendMsg(NDSendMsg *pmsg, NDINT32 flag)
{
	nd_assert(_h_connector) ;
	return nd_connector_send(_h_connector,(nd_packhdr_t*) (pmsg->GetMsgAddr()), flag) ;
}

NDINT32 NDConnector::Update(ndtime_t wait_time)
{

	NDINT32 ret;
	//nd_msgui_buf msg_recv;
	if(_h_connector->type==ND_UDT) {
		nd_usermsgbuf_t msg_recv;
		ret = nd_connector_waitmsg(_h_connector, (nd_packetbuf_t *)&msg_recv,wait_time);
		if(ret > 0) {			
			//msg_entry(connect_handle, &msg_recv) ;
			nd_translate_message(_h_connector, (nd_packhdr_t*)&msg_recv) ;
			return 0;
		}
		else {
			return -1 ;
		}
		
	}
	else {
		return nd_connector_update(_h_connector,wait_time) ;
	}
}

NDINT32 NDConnector::WaitMsg(nd_usermsgbuf_t *msgbuf, ndtime_t wait_time)
{
	return nd_connector_waitmsg(_h_connector, (nd_packetbuf_t *)msgbuf,wait_time);
}
void NDConnector::InstallMsgFunc(nd_usermsg_func func, ndmsgid_t maxid, ndmsgid_t minid)
{
	if(_h_connector)
		nd_msgentry_install(_h_connector, func,  maxid,  minid,EPL_CONNECT) ;
}

NDINT32 NDConnector::CheckValid()
{
	if(!_h_connector)
		return 0 ;
	return 	nd_connector_valid((nd_netui_handle)_h_connector) ;
}
